import request from '../../utils/request'
import { showError, showSuccess } from '../../utils/util'
import JwtUtil from '../../utils/jwt'  // 引入JWT解析工具

Page({
  data: {
    post: null,
    postId: null,
    loading: true,
    isLiked: false,
    likeCount: 0,
    userInfoReady: false,
    isCreator: false,
    hasApplied: false,
    teamMembers: [],
    showApplyModal: false
  },

  onLoad: function(options) {
    console.log('=== 帖子详情页开始加载 ===')
    console.log('页面参数:', options)

    if (options && options.id) {
      this.setData({ postId: options.id })
      this.tryParseUserIdFromToken()
    } else {
      showError('帖子ID不存在')
      wx.navigateBack()
    }
  },

  // 尝试从token解析用户ID
  tryParseUserIdFromToken: function() {
    const app = getApp()
    const token = wx.getStorageSync('token')
    
    if (token) {
      console.log('发现token，尝试解析用户ID')
      try {
        const userId = JwtUtil.getUserId(token)
        if (userId) {
          console.log('从token解析出用户ID:', userId)
          app.globalData.userId = userId
          app.globalData.userInfoReady = true
          this.setData({ userInfoReady: true })
          this.loadPostDetail()
          return
        }
      } catch (error) {
        console.error('解析token失败:', error)
      }
    }
    
    // 如果解析失败或没有token，检查现有用户信息
    if (app.globalData.userInfo && app.globalData.userInfo.userId) {
      console.log('使用现有用户信息中的ID:', app.globalData.userInfo.userId)
      app.globalData.userId = app.globalData.userInfo.userId
      app.globalData.userInfoReady = true
      this.setData({ userInfoReady: true })
      this.loadPostDetail()
    } else {
      console.log('没有用户ID，直接加载帖子详情')
      this.setData({ userInfoReady: true })
      this.loadPostDetail()
    }
  },

  // 加载帖子详情
  loadPostDetail: function() {
    const that = this
    const app = getApp()

    console.log('开始加载帖子详情，ID:', this.data.postId)
    console.log('当前用户ID:', app.globalData.userId)

    this.setData({ loading: true })

    // 并行加载帖子详情和队伍成员
    Promise.all([
      this.loadPostInfo(),
      this.loadTeamMembers(),
      this.checkApplyStatus()
    ]).then(([postData, members, applyStatus]) => {
      console.log('所有数据加载完成:', { postData, members, applyStatus })

      // 检查当前用户是否是创建者
      const isCreator = postData.userId === app.globalData.userId
      console.log('是否是创建者:', isCreator, '帖子创建者:', postData.userId, '当前用户:', app.globalData.userId)

      that.setData({
        post: postData,
        isCreator: isCreator,
        hasApplied: applyStatus,
        teamMembers: members,
        loading: false
      })

      console.log('页面数据设置完成:', that.data)
    }).catch(error => {
      console.error('加载帖子详情失败:', error)
      that.setData({ loading: false })
      showError('加载失败，请重试')
    })
  },

  // 其他方法保持不变...
  // ... 你原有的其他方法

  // 加载帖子信息
  loadPostInfo: function() {
    const that = this
    return new Promise((resolve, reject) => {
      request.get('/posts/' + this.data.postId)
          .then(postData => {
            console.log('帖子信息加载成功:', postData)

            // 标准化数据格式
            const normalizedPost = that.normalizePostData(postData)
            console.log('标准化后的帖子数据:', normalizedPost)

            // 检查点赞状态
            return that.checkLikeStatus(normalizedPost).then(postWithLike => {
              resolve(postWithLike)
            })
          })
          .catch(error => {
            console.error('加载帖子信息失败:', error)
            reject(error)
          })
    })
  },

  // 标准化帖子数据
  normalizePostData: function(postData) {
    console.log('标准化帖子数据:', postData)

    // 如果直接是帖子对象
    if (postData && postData.id) {
      return {
        id: postData.id,
        userId: postData.userId,
        title: postData.title || '无标题',
        content: postData.content || '无内容',
        category: postData.category || '其他',
        maxMembers: postData.maxMembers || 10,
        currentMembers: postData.currentMembers || 1,
        location: postData.location || '未知地点',
        startTime: postData.startTime,
        endTime: postData.endTime,
        status: postData.status || '招募中',
        viewCount: postData.viewCount || 0,
        likeCount: postData.likeCount || 0,
        applyCount: postData.applyCount || 0,
        createTime: postData.createTime,
        tags: postData.tags || []
      }
    }

    // 如果是包装对象 { data: {}, code: 200 }
    if (postData && postData.data) {
      return this.normalizePostData(postData.data)
    }

    console.warn('未知的帖子数据格式:', postData)
    return {}
  },

  // 检查点赞状态
  checkLikeStatus: function(post) {
    const that = this
    const app = getApp()

    return new Promise((resolve) => {
      // 如果没有用户ID，直接返回
      if (!app.globalData.userId) {
        console.log('没有用户ID，跳过点赞状态检查')
        resolve(post)
        return
      }

      request.get('/team/check-like', {
        postId: post.id,
        userId: app.globalData.userId
      }).then(likeStatus => {
        console.log('点赞状态检查结果:', likeStatus)
        const isLiked = likeStatus.isLiked || likeStatus.liked || false

        that.setData({
          isLiked: isLiked,
          likeCount: post.likeCount || 0
        })

        resolve(post)
      }).catch(error => {
        console.warn('检查点赞状态失败:', error)
        resolve(post)
      })
    })
  },

  // 加载队伍成员
  loadTeamMembers: function() {
    return new Promise((resolve) => {
      request.get('/team/members', { postId: this.data.postId })
          .then(members => {
            console.log('队伍成员加载成功:', members)

            // 标准化成员数据
            let normalizedMembers = []
            if (Array.isArray(members)) {
              normalizedMembers = members
            } else if (members && members.data) {
              normalizedMembers = members.data
            }

            resolve(normalizedMembers)
          })
          .catch(error => {
            console.warn('加载队伍成员失败:', error)
            resolve([]) // 失败时返回空数组
          })
    })
  },

  // 检查申请状态
  checkApplyStatus: function() {
    const app = getApp()

    return new Promise((resolve) => {
      // 如果没有用户ID，直接返回未申请
      if (!app.globalData.userId) {
        resolve(false)
        return
      }

      request.get('/team/check-apply', {
        postId: this.data.postId,
        userId: app.globalData.userId
      }).then(applyStatus => {
        console.log('申请状态检查结果:', applyStatus)
        const hasApplied = applyStatus.hasApplied || applyStatus.applied || false
        resolve(hasApplied)
      }).catch(error => {
        console.warn('检查申请状态失败:', error)
        resolve(false) // 失败时默认未申请
      })
    })
  },

  // 点赞/取消点赞
  onLikeTap: function() {
    const that = this
    const app = getApp()
    const { isLiked, post } = this.data

    if (!app.globalData.userId) {
      showError('请先登录')
      return
    }

    console.log('点赞操作:', { isLiked: isLiked, postId: post.id })

    const action = isLiked ? 'unlike' : 'like'
    const url = `/posts/${post.id}/${action}`

    request.post(url, { userId: app.globalData.userId })
        .then(result => {
          console.log('点赞操作成功:', result)

          const newLikeCount = isLiked ?
              Math.max(0, (post.likeCount || 1) - 1) :
              (post.likeCount || 0) + 1

          // 更新帖子数据和UI
          const updatedPost = {
            ...post,
            likeCount: newLikeCount
          }

          that.setData({
            isLiked: !isLiked,
            post: updatedPost,
            likeCount: newLikeCount
          })

          showSuccess(isLiked ? '取消点赞' : '点赞成功')
        })
        .catch(error => {
          console.error('点赞操作失败:', error)
          showError('操作失败，请重试')
        })
  },

  // 申请加入队伍
  onApplyTap: function() {
    const that = this
    const app = getApp()
    const { post, isCreator, hasApplied } = this.data

    console.log('申请加入队伍:', {
      postId: post.id,
      isCreator: isCreator,
      hasApplied: hasApplied,
      currentUserId: app.globalData.userId
    })

    if (!app.globalData.userId) {
      showError('请先登录')
      return
    }

    // 检查是否是队长
    if (isCreator) {
      showError('队长不能申请自己的队伍')
      return
    }

    // 检查是否已申请
    if (hasApplied) {
      showError('您已经申请过该队伍')
      return
    }

    // 显示申请确认弹窗
    this.setData({ showApplyModal: true })
  },

  // 确认申请
  onConfirmApply: function() {
    const that = this
    const app = getApp()
    const { post } = this.data

    console.log('确认申请加入队伍:', {
      postId: post.id,
      userId: app.globalData.userId
    })

    this.setData({ showApplyModal: false })

    request.post('/team/apply', {
      postId: post.id,
      userId: app.globalData.userId
    }).then(result => {
      console.log('申请成功:', result)

      that.setData({ hasApplied: true })
      showSuccess('申请成功，等待队长审核')

    }).catch(error => {
      console.error('申请失败:', error)
      // 显示具体的错误信息
      if (error.message && error.message.includes('队长不能申请自己的队伍')) {
        showError('队长不能申请自己的队伍')
      } else if (error.message && error.message.includes('已经申请过')) {
        showError('您已经申请过该队伍')
      } else {
        showError(error.message || '申请失败，请重试')
      }
    })
  },

  // 取消申请
  onCancelApply: function() {
    this.setData({ showApplyModal: false })
    console.log('取消申请')
  },

  // 分享
  onShareAppMessage: function() {
    const { post } = this.data
    return {
      title: post.title || '组队邀请',
      path: `/pages/post-detail/post-detail?id=${post.id}`
    }
  },

  // 联系队长
  onContactCaptain: function() {
    const { post } = this.data
    showSuccess('联系功能开发中')
    console.log('联系队长:', post.userId)
  },

  // 查看成员详情
  onMemberTap: function(e) {
    const member = e.currentTarget.dataset.member
    console.log('点击成员:', member)
  },

  // 页面卸载
  onUnload: function() {
    console.log('帖子详情页卸载')
  }
})